package com.ihome.android.academy.db;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

import com.ihome.android.util.log.LogUtil;

/**
 * 数据库操作
 * 
 * @author Emerson
 */
public class DBProvider extends ContentProvider {

	private static final String		tag						= DBProvider.class.getSimpleName();
	public static final String		AUTHORITY				= "com.ihome.android.academy.AcademyProvider";

	private DBHelper				dbHelper;
	private static final UriMatcher	sUriMatcher				= new UriMatcher(UriMatcher.NO_MATCH);
	private static final int		DOWNLOADS				= 1;
	private static final int		DOWNLOADS_ID			= 2;

	private static final int		UPDATE_APP				= 11;
	private static final int		UPDATE_APP_ID			= 12;
	static {

		sUriMatcher.addURI(AUTHORITY, "downloads", DOWNLOADS);
		sUriMatcher.addURI(AUTHORITY, "downloads/#", DOWNLOADS_ID);

		sUriMatcher.addURI(AUTHORITY, "update_app", UPDATE_APP);
		sUriMatcher.addURI(AUTHORITY, "update_app/#", UPDATE_APP_ID);
	}

	private static final String		DATABASE_NAME			= "Market2.db";
	private static final int		DATABASE_VERSION		= 1;

	public static final String		TABLE_NAME_UPDATEAPP	= UpdateApp.TABLE_NAME;

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int count = 0;
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		switch (sUriMatcher.match(uri)) {
		case UPDATE_APP:
			count = db.delete(TABLE_NAME_UPDATEAPP, selection, selectionArgs);
			break;
		case UPDATE_APP_ID:
			count = db.delete(TABLE_NAME_UPDATEAPP, UpdateAppInfo.KEY_PKGNAME, new String[] { uri.getPathSegments()
					.get(1) });
			break;
		}
		db.close();
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
		case UPDATE_APP:
			return UpdateApp.CONTENT_TYPE;
		case UPDATE_APP_ID:
			return UpdateApp.CONTENT_ITEM_TYPE;
		default:
			throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		LogUtil.d(tag, "insert " + values.toString());
		long rowID = 0;
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		try {
			switch (sUriMatcher.match(uri)) {
			case UPDATE_APP:
				values.put(UpdateAppInfo.KEY_TIMESTAMP, System.currentTimeMillis());
				rowID = db.insert(TABLE_NAME_UPDATEAPP, null, values);
				break;
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
		if (rowID > 0) {
			Uri _uri = ContentUris.withAppendedId(uri, rowID);
			getContext().getContentResolver().notifyChange(_uri, null);
			return _uri;
		}
		return null;
		// throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
		dbHelper = new DBHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		LogUtil.d(tag, "query uri = " + uri);
		if (null != projection)
			for (String str : projection)
				LogUtil.d(tag, "projection = " + str);
		LogUtil.d(tag, "selection = " + selection);
		if (null != selectionArgs)
			for (String str : selectionArgs)
				LogUtil.d(tag, "selectionArgs = " + str);
		LogUtil.d(tag, "sortOrder = " + sortOrder);

		String orderBy = "timeStamp DESC";

		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		switch (sUriMatcher.match(uri)) {
		case UPDATE_APP:
			qb.setTables(TABLE_NAME_UPDATEAPP);
			orderBy = UpdateApp.DEFAULT_SORT_ORDER;
			break;
		case UPDATE_APP_ID:
			qb.setTables(TABLE_NAME_UPDATEAPP);
			qb.appendWhere(UPDATE_APP_ID + "=" + uri.getPathSegments().get(1));
			orderBy = UpdateApp.DEFAULT_SORT_ORDER;
			break;
		default:
			// throw new IllegalArgumentException("Unknown URI " + uri);
			LogUtil.d(tag, new IllegalArgumentException("Unknown URI " + uri).toString());
		}

		if (!TextUtils.isEmpty(sortOrder))
			orderBy = sortOrder;

		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
		// db.close();
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		int count = 0;
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		switch (sUriMatcher.match(uri)) {
		case UPDATE_APP:
			values.put(UpdateAppInfo.KEY_TIMESTAMP, System.currentTimeMillis());
			count = db.update(TABLE_NAME_UPDATEAPP, values, selection, selectionArgs);
			break;
		case UPDATE_APP_ID:
			values.put(UpdateAppInfo.KEY_TIMESTAMP, System.currentTimeMillis());
			count = db.update(TABLE_NAME_UPDATEAPP, values, UpdateAppInfo.KEY_PKGNAME, new String[] { uri
					.getPathSegments().get(1) });
			break;
		}
		db.close();
		return count;
	}

	private class DBHelper extends SQLiteOpenHelper {

		public static final String	CREATE_TABLE_UPDATE_APP	= "CREATE TABLE " + TABLE_NAME_UPDATEAPP
																	+ " (_id INTEGER PRIMARY KEY,"
																	+ UpdateAppInfo.KEY_PKGNAME
																	+ " TEXT UNIQUE NOT NULL,"
																	+ UpdateAppInfo.KEY_FILE_PATH + " TEXT,"
																	+ UpdateAppInfo.KEY_NEEDUPDATE + " BOOLEAN,"
																	+ UpdateAppInfo.KEY_VERSION + " TEXT,"
																	+ UpdateAppInfo.KEY_APPNAME + " TEXT,"
																	+ UpdateAppInfo.Key_APP_ID + " INTEGER,"
																	+ UpdateAppInfo.KEY_ICONURL + " TEXT,"
																	+ UpdateAppInfo.KEY_RATE + " FLOAT,"
																	+ UpdateAppInfo.KEY_USERNUM + " INTEGER,"
																	+ UpdateAppInfo.KEY_APKFILESIZE + " TEXT,"
																	+ UpdateAppInfo.KEY_UPDATETIME + " TEXT,"
																	+ UpdateAppInfo.KEY_UPDATEVERSIONDES + " TEXT,"
																	+ UpdateAppInfo.KEY_URL + " TEXT,"
																	+ UpdateAppInfo.KEY_FILENAME + " TEXT,"
																	+ UpdateAppInfo.KEY_STATUS + " INTEGER,"
																	+ UpdateAppInfo.KEY_TIMESTAMP + " LONG);";

		public DBHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {

			db.execSQL(CREATE_TABLE_UPDATE_APP);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

			db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_UPDATEAPP);
			onCreate(db);
		}
	}

}
